package com.hl.card.modular.packBack.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.plugins.Page;
import com.hl.card.common.constant.factory.PageFactory;
import com.hl.card.common.controller.BaseController;
import com.hl.card.common.persistence.model.Bill;
import com.hl.card.modular.packBack.service.BillService;


@Controller
@RequestMapping("/bill")
public class BillController  extends BaseController{
	private String PREFIX = "/packback/bill/";
    @Autowired
    private BillService  billService;
    @Value("${auth_count}")
    private Integer auth_count;
	@Autowired
	private RedisTemplate<String,String>  redisTemplate;
	/**
	 * 跳转社区管理员列表
	 * 
	 * @return
	 */
	@RequestMapping("/index")
	public String index() {
		return PREFIX + "bill.html";
	}
	/**
	 * 查询列表
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping("/list")
	@ResponseBody
	public Object list(Bill bill,HttpServletRequest request) {
		String sort = request.getParameter("sort");
		String order = request.getParameter("order");
		Page<Bill> page = new PageFactory<Bill>().defaultPage();
		List<Bill> list = billService.list(page,bill,sort,order);
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("rows", list);
		result.put("total", page.getTotal());
		return result;
	}
	
	/**
	 * 导出
	 */
	@RequestMapping(value = "/exportExcel")
	@ResponseBody
	public void exportExcel(Bill bill,HttpServletResponse response) {
		List<Map<String,Object>> list=billService.exportExcel(bill);
		// 声明一个头部信息
		List<String> headers = Arrays.asList("账单编号", "出账时间", "用户帐号","社区编号","本期认证数","状态","结算时间");
		List<String> header_cloums = Arrays.asList("bill_no", "time", "account", "community_code", "num", "status", "settle_time");
		// 声明一个工作薄
		HSSFWorkbook workbook = new HSSFWorkbook();
		// 生成一个表格
		HSSFSheet sheet = workbook.createSheet();
		sheet.setDefaultColumnWidth((short) 24);
		HSSFCellStyle style = workbook.createCellStyle();
		style.setBorderBottom(BorderStyle.THIN); // 下边框
		style.setBorderLeft(BorderStyle.THIN);// 左边框
		style.setBorderTop(BorderStyle.THIN);// 上边框
		style.setBorderRight(BorderStyle.THIN);// 右边框
		style.setAlignment(HorizontalAlignment.CENTER); // 居中
		style.setFillForegroundColor((short) 13);// 设置背景色
		style.setFillPattern(FillPatternType.SOLID_FOREGROUND);

		HSSFCellStyle style2 = workbook.createCellStyle();
		style2.setBorderBottom(BorderStyle.THIN); // 下边框
		style2.setBorderLeft(BorderStyle.THIN);// 左边框
		style2.setBorderTop(BorderStyle.THIN);// 上边框
		style2.setBorderRight(BorderStyle.THIN);// 右边框
		style2.setAlignment(HorizontalAlignment.CENTER); // 居中
		HSSFRow row = sheet.createRow(0);

		for (String head : headers) {
			HSSFCell cell = row.createCell(headers.indexOf(head));
			HSSFRichTextString richString = new HSSFRichTextString(head);
			HSSFFont font3 = workbook.createFont();
			font3.setBold(true);
			richString.applyFont(font3);
			cell.setCellValue(richString);
			cell.setCellStyle(style);

		}
		for (int i = 0; i < list.size(); i++) {
			row = sheet.createRow(i + 1);
			for(int j=0;j<header_cloums.size();j++)
			{
				HSSFCell cell = row.createCell(j);
				String textValue="";
				if(header_cloums.get(j).equals("status"))
				{
					textValue=list.get(i).get(header_cloums.get(j))+"";
					if(textValue.equals("0"))
					{
						textValue="未结算";
					}else
					{
						textValue="已结算";
					}
				}else{
				    textValue = list.get(i).get(header_cloums.get(j))+"";
				}
				HSSFRichTextString richString = new HSSFRichTextString(textValue.equals("null")?"":textValue);  
				cell.setCellValue(richString);
				cell.setCellStyle(style2);
			}
		}

		response.setContentType("application/octet-stream");
		try{
		response.setHeader("Content-disposition", "attachment;filename="
				+ new String(("认证账单结算.xls").getBytes("UTF-8"), "ISO8859-1"));// 默认Excel名称
		response.flushBuffer();
		workbook.write(response.getOutputStream());
		}catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}
	@RequestMapping("/switchStatus")
	@ResponseBody
	public Object switchStatus(Integer status, Integer id) {
		if (id == null) {
			return super.FailuerTip("ID不能为空");
		}
		if (status == null) {
			return super.FailuerTip("状态不能为空");
		}
		billService.switchStatus(status, id);
		return super.SUCCESS_TIP;
	}
	
	@RequestMapping("/add")
	@ResponseBody
	public Object add() {
		Map<String,Object> map=new HashMap<String, Object>();
		map.put("auth_count", auth_count);
		int count=billService.findBillCount(map);
		if(count==0)
		{
			return super.FailuerTip("暂无最新可生成账单!");
		}
		boolean result= redisTemplate.hasKey("redis_bill_lock");
		if(result)
		{
			String redis_bill_lock=redisTemplate.opsForValue().get("redis_bill_lock");
			if(redis_bill_lock.equals("open"))
			{
				return super.FailuerTip("审核中...请稍后再出账!");
			}
		}
		redisTemplate.opsForValue().set("redis_bill_lock", "open");
		try{
			billService.add();
		}catch(Exception ex)
		{
			ex.printStackTrace();
			throw ex;
		}finally
		{
			redisTemplate.opsForValue().set("redis_bill_lock", "close");
		}
		return super.SUCCESS_TIP;
	}
	
}
